﻿using System.Text;
using Dapper;
using Microsoft.Data.SqlClient;
using Production.CommonLib.Models;
using Swimj.CommonLib.Base;
using Swimj.DataCore;

namespace Production.ApplicationLib.Queries
{
    public class ProductionPlanQueries : IProductionPlanQueries
    {
        private readonly string _defaultConnStr;

        public ProductionPlanQueries(string defaultConnStr)
        {
            _defaultConnStr = defaultConnStr;
        }

        public async Task<PaginatedResult<ProductionPlanInfoResponseDto>?> QueryProductionPlansByPage(ProductionPlanSearchRequestDto model)
        {
            IEnumerable<ProductionPlanInfoResponseDto>? data = null;
            int totalCount = 0;
            using (var db = new SqlConnection(_defaultConnStr))
            {
                var query = new Query(db);

                StringBuilder sqlBuilder = new StringBuilder(@"
select t.id,
       t.plancode,
       t.planname,
       t.orderid,
       t.ordercode,
       t.plantype,
       t.docketdate,
       t.docketstatus,
       t.expectstartdate,
       t.expectenddate,
       t.prioritylevel,
       t.scheduletype,
       t.productid,
       t.productcode,
       t.productname,
       t.quality,
       t.description,
       t.datastate,
       t.createdby,
       t.createdon,
       t.lastmodifiedby,
       t.lastmodifiedon,
       t.deletedby,
       t.deletedon
from MES_PRODUCTIONPLAN t where 1 = 1 ");

                query.BuildPageQueries(model.Page, model.Limit, sqlBuilder.ToString());

                data = await db.QueryAsync<ProductionPlanInfoResponseDto>(query.SqlPage);

                totalCount = await db.ExecuteScalarAsync<int>(query.SqCount);
            }

            return await PaginatedResult<ProductionPlanInfoResponseDto>.SuccessAsync(data.ToList(), totalCount,
                model.Page,
                model.Limit);
        }

        public Task<Result<IList<ProductionPlanInfoResponseDto>>?> QueryProductionPlans(ProductionPlanSearchRequestDto model)
        {
            throw new NotImplementedException();
        }
    }
}